import { defineStore } from 'pinia'
import { getGoodsList } from '@/service/module/goods/goods'

interface GoodsType {
  goodsList: any[]
  page: number
  pageSize: number
  hasMore: boolean
  loading: boolean
  searchParams: any
}

export const useGoodsStore = defineStore('useGoods', {
  state: (): GoodsType => ({
    goodsList: [],
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false,
    searchParams: {
      sortField: '',
      sortOrder: '',
      description: '',
      priceMin: '',
      priceMax: '',
    },
  }),
  actions: {
    // 初始化或刷新
    async initGoodsList(params = {}) {
      this.page = 1
      this.hasMore = true
      this.goodsList = []
      await this.loadMoreGoods({ pageSize: this.pageSize, ...params })
    },
    // 加载更多
    async loadMoreGoods(params = {}) {
      if (this.loading || !this.hasMore) return
      this.loading = true
      const res = await getGoodsList({ pageNo: this.page, pageSize: this.pageSize, ...params })

      const records = res.data.data.records || []
      if (this.page === 1) {
        this.goodsList = records
      } else {
        this.goodsList = [...this.goodsList, ...records]
      }
      this.hasMore = records.length === this.pageSize
      this.page += 1
      this.loading = false
    },
  },
})
